<template>
  <div class="w-full h-full">
    <mci-dialog
      v-model="visible"
      :title="title"
      width="1000px"
      :draggable="true"
      :append-to-body="true"
      :confirm-handle="handleConfirm"
      :top="'30vh'"
      @close="handleClosed"
    >
      <div style="min-height: 42vh">
        <!-- 代码框 -->
        <!-- <ApiModelCode ref="codeRef" @mounted-finish="handleCodeMounted" /> -->
        <CodeMirror
          ref="codeRef"
          v-model="javaCode"
          :lang="lang"
          :basic="true"
          :style="{height: '400px'}"
          class="w-full  min-h-20 bd"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <mci-button @click="visible = false">取消</mci-button>
          <mci-button type="primary" @click="handleConfirm"> 确定 </mci-button>
        </span>
      </template>
    </mci-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import { MciDialog, MciButton } from '@/components/base';
import CodeMirror from 'vue-codemirror6';
import { java } from '@codemirror/lang-java';

const emit = defineEmits(['closed', 'value']);

// onMounted(() => {
//   nextTick(function () {
//     !initFinish.value && templateID.value && codeRef.value?.initData(templateID.value);
//   });
// });

const visible = ref(false);
const title = ref('组装请求参数和Header的脚本');
// 代码
const javaCode = ref('');
 // 语言
 const lang = java();

// const templateID = ref('');
// const initFinish = ref(false);
const handleClosed = () => {
  visible.value = false;
  emit('closed');
};

const codeRef = ref<any>(null);

const handleConfirm = () => {
  // const { code } = codeRef.value?.getData();
  const val = codeRef.value?.json;
  emit('value', val?.doc);
  visible.value = false;
};

// 初始化
const initData = async (code: any) => {
  visible.value = true;
  javaCode.value = code;
  // templateID.value = id;
  // if (codeRef.value) {
  //   initFinish.value = true;
  //   codeRef.value?.initData(templateID.value);
  // } else {
  //   initFinish.value = false;
  // }
};

// 代码框挂载完成
// const handleCodeMounted = () => {
  // templateID.value = id;
  // if (codeRef.value) {
  //   initFinish.value = true;
  //   codeRef.value?.initData(templateID.value);
  // } else {
  //   initFinish.value = false;
  // }
// };

// 代码更新
// const handleCodeUpdate = (val: any) => {
//   newCode.value = val;
// };

// 获取值
const getData = () => {
  // return { code: codeRef.value?.getData() };
  const val = codeRef.value?.json;
  return { code: val?.doc };
};

defineExpose({
  initData,
  getData
});
</script>
